package org.ala.shopping_test.shopping_center.repository.order_seller.router;

import java.util.Map;

import org.ala.shopping_test.shopping_center.repository.order_seller.query.ShoppingOrderSellerQuery;
import org.ala.shopping_test.shopping_center.repository.shard_key.ShoppingOrderBuyerSellerShardKey;
import org.ala.shopping_test.shopping_center.repository.shard_key.ShoppingOrderBuyerSellerShardKeyRouter;
import org.ala.tiktools.sharddb.mybatis.router.IShardRouter;
import org.ala.tiktools.sharddb.mybatis.router.ShardInfo;
import org.ala.tiktools.sharddb.mybatis.router.shard_key_router.IShardKeyConverter;
import org.ala.tiktools.sharddb.mybatis.router.shard_key_router.IShardKeyRouter;
import org.ala.tiktools.sharddb.mybatis.router.shard_key_router.ShardKeyRouteWorker;

/**
 *	分库分表路由器 (shopping_order_seller)
 *  订单总表
 *
 *	@author 骆毅 (ala)
 *	@date 2025-03-23 21:27:47
 */
public class ShoppingOrderSellerQueryRouter implements IShardRouter<ShoppingOrderSellerQuery> {
    /**
     *  分片建路由器
     */
    protected IShardKeyRouter<ShoppingOrderBuyerSellerShardKey> router = new ShoppingOrderBuyerSellerShardKeyRouter();
    /**
     *  分片建转换器
     */
    protected IShardKeyConverter<ShoppingOrderSellerQuery, ShoppingOrderBuyerSellerShardKey> converter = new IShardKeyConverter<ShoppingOrderSellerQuery, ShoppingOrderBuyerSellerShardKey>() {
        @Override
        public ShoppingOrderBuyerSellerShardKey convert(ShoppingOrderSellerQuery d) {
            return ShoppingOrderBuyerSellerShardKey.build()
                    .id(d.getBuyerId())
                    .timestamp(d.getCreateTime())
                    .timestampGte(d.getCreateTimeGte() != null ? d.getCreateTimeGte() : (d.getCreateTimeGt() != null ? d.getCreateTimeGt() + 1 : -1))
                    .timestampLte(d.getCreateTimeLte() != null ? d.getCreateTimeLte() : (d.getCreateTimeLt() != null ? d.getCreateTimeLt() - 1 : -1));
        }

        @Override
        public ShoppingOrderSellerQuery deConvert(ShoppingOrderSellerQuery d, ShoppingOrderBuyerSellerShardKey k) {
            return d.copy().buyerId(k.getId())
                    .createTime(k.getTimestamp() > 0 ? k.getTimestamp() : null)
                    .createTimeGte(k.getTimestampGte() > 0 ? k.getTimestampGte() : null)
                    .createTimeLte(k.getTimestampLte() > 0 ? k.getTimestampLte() : null);
        }
    };


    /**
     * 分库分表
     */
    @Override
    public Map<ShardInfo, ShoppingOrderSellerQuery> route(ShoppingOrderSellerQuery d) {
        return ShardKeyRouteWorker.instance().route(d, router, converter);
    }
}